package com.leinao.file.controller;

import com.alibaba.fastjson.JSON;
import com.leinao.commons.Response;
import com.leinao.constant.Constant;
import com.leinao.constant.FileErrorEnum;
import com.leinao.file.dto.FileUploadDto;
import com.leinao.file.model.FileResource;
import com.leinao.file.service.FileService;
import com.leinao.login.dto.LoginResultDto;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @Description 文件上传控制类
 * @author lizi
 * @date 2018/10/16 上午11:19
 * @Version 1.0
 */
@RestController
@CrossOrigin
public class FileUploadController {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private FileService fileService;

	@Autowired
	private HttpServletRequest request;
	
	@ApiOperation(value = "文件上传", notes = "文件上传结果")
	@PostMapping(value = "/file/upload")
	public Response<Void> fileUpload(FileUploadDto fileUploadDto) {
		logger.info("fileUpload param fileUploadBean: {}", fileUploadDto);
		if (StringUtils.isBlank(fileUploadDto.getDir())) {
			return Response.error(200, FileErrorEnum.PARAM_ERROR.getSeq(), FileErrorEnum.PARAM_ERROR.getDesc());
		}

		// 获取登录用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );

		fileUploadDto.setUserId(userInfo.getUserId());
		return fileService.upload(fileUploadDto);
	}

	@ApiOperation(value = "文件上传七牛", notes = "文件上传七牛结果")
	@PostMapping(value = "/file/qiniu/upload")
	public Response<FileResource> qiniuFileUpload(FileUploadDto fileUploadDto) {
		logger.info("qiniuFileUpload param fileUploadBean: {}", fileUploadDto);
		if (fileUploadDto.getFile() == null) {
			return Response.error(200, FileErrorEnum.PARAM_ERROR.getSeq(), FileErrorEnum.PARAM_ERROR.getDesc(), null);
		}

		return fileService.qiniuFileUpload(fileUploadDto.getFile());
	}
}
